/**
 * 
 */
package com.uva.dbcs.utilidades.persistencia;

import java.util.List;

import javax.persistence.EntityManager;

/**
 * Dao genérico que implementa las operaciones más comunes y
 * que son reutilizadas por todos los daos especificos.
 * 
 * @author seten
 * 
 * @param <T>
 *            Tipo de la entity
 * @param <P>
 *            Tipo de la clave primaria
 */
public abstract class GenericAbstractDAO<T, P> implements GenericDAO<T, P>{

	private Class<T> entityClass;

	private String entityName;

	public abstract EntityManager getEntityManager();

	public GenericAbstractDAO(Class<T> entityClass) {
		this.entityClass = entityClass;
		this.entityName = this.entityClass.getSimpleName();
	}

	@Override
	public void create(T entity) {
		getEntityManager().persist(entity);
	}

	@Override
	public void delete(T entity) {
		getEntityManager().remove(entity);
	}

	@Override
	public void merge(T entity) {
		getEntityManager().merge(entity);
	}

	@Override
	public T find(P id) {
		return getEntityManager().find(entityClass, id);
	}

	@Override
	public List<T> findAll() {

		return getEntityManager().createQuery(
				"Select t from " + entityName + " t", entityClass)
				.getResultList();
	}

	@Override
	public List<T> findWithPagination(int first, int size) {
		
		return getEntityManager().createQuery(
				"Select t from " + entityName + " t", entityClass)
				.setFirstResult(first)
				.setMaxResults(size)
				.getResultList();
	}
	
	@Override
	public int count() {

		return getEntityManager()
				.createQuery("Select t from " + entityName + " t", entityClass)
				.getResultList().size();
	}
	
	@Override
	public void refresh(T entity){
		
		getEntityManager().refresh(entity);
	}
	
	@Override
	public void flush(){
		
		getEntityManager().flush();
	}

}
